import getUserTempId from "@/utils/userTempId"
import { requestLogin, requestUserInfo, requestLogout } from "@/api"

const state = {
  userTempId: getUserTempId(),
  token: localStorage.getItem("user_Token"),
  nickName: ""
}

const mutations = {
  SET_TOKEN_STATE(state, value) {
    state.token = value
  },
  SET_NICKNAME_STATE(state, value) {
    state.nickName = value
  },
  SET_LOGOUT_STATE(state) {
    state.token = ""
    state.nickName = ""
    localStorage.removeItem("user_Token")
  }
}

const actions = {
  async getToken({ commit }, userInfo) {
    const re = await requestLogin(userInfo)
    commit("SET_TOKEN_STATE", re.token)
    // 将token放到本地存储中做数据持久化
    localStorage.setItem("user_Token", re.token)
  },
  async getUsername({ commit }) {
    try {
      const re = await requestUserInfo()
      commit("SET_NICKNAME_STATE", re.nickName)
    } catch (e) {
      localStorage.removeItem("user_Token")
      return Promise.reject()
    }
  },
  async getLogout({ commit }) {
    await requestLogout()
    commit("SET_LOGOUT_STATE")
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}